<template>
    <div class="tableList">
        <el-table :data="tableList" border style="width: 100%;" @sort-change="handleSortChange"
            :header-cell-style="{background:'#fafafa',color:'#000',fontWeight:400,fontSize:'12px'}" v-loading="loading" element-loading-text="加载中"
            element-loading-background="rgba(250, 250, 250, 0.5)" element-loading-spinner="el-icon-loading"
            :cell-style="{color:'#5a5a5a',fontSize:'12px',fontWeight:400}"
            @select-all="selectAll" ref='selTable' id="outTable"
            @select="onTableSelect" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column
                v-for="(item, i) in tableGroup"
                :label="item.name"
                :prop="item.label"
                :min-width="item.width"
                :sortable="item.sortable"
                :fixed="item.fixed"
                show-overflow-tooltip
                :key='i'
            >
                <template slot-scope="scope">
                    <code v-if="item.label == 'code' && menu == '工艺路线'">
                        <span style='color:#02b980;cursor: pointer;' @click="codeDetail(scope.row)">{{scope.row[item.label]}}</span>
                    </code>
                    <code v-else-if="item.label == 'pricing' || item.label == 'pricingMethod'">
                        {{scope.row[item.label] | pricingMethod}}
                    </code>
                    <code v-else-if="item.label == 'attribute'">
                        {{ enumCon.productAttribute(scope.row[item.label]) }}
                    </code>
                    <code v-else>
                        <code v-if='customImgSet(item.label, scope.row)'>
                            <p v-if='(JSON.parse(scope.row[item.label])).length <= 2'>
                                <img 
                                    :src="$global.uploadUrl + k.url" 
                                    alt="" 
                                    v-for="(k, i) in JSON.parse(scope.row[item.label])" :key="i"
                                    class="customImg"
                                    @click='costomImgPreview(i+1, (JSON.parse(scope.row[item.label])).length, JSON.parse(scope.row[item.label]))'
                                >
                            </p>
                            <p v-else>
                                <img
                                    :src="$global.uploadUrl + JSON.parse(scope.row[item.label])[0].url" 
                                    alt="" 
                                    class="customImg" 
                                    @click='costomImgPreview(1, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))'
                                >
                                <span class='customImgMoreBox'>
                                    <div class='customImgMore'
                                        @click='costomImgPreview(2, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))'
                                    >
                                        <el-popover
                                            placement="top"
                                            max-width="400"
                                            trigger="hover">
                                            <div class='customImgMore' slot="reference">+{{ JSON.parse(scope.row[item.label]).length - 2 }}</div>
                                            <img 
                                                :src="$global.uploadUrl + k.url" 
                                                alt="" 
                                                v-for="(k, i) in JSON.parse(scope.row[item.label])" :key="i"
                                                style="margin-right:10px"
                                                width='60px'
                                                height='60px'
                                                @click="costomImgPreview(i+1, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))"
                                            >
                                        </el-popover>
                                    </div>
                                    <img 
                                        :src="$global.uploadUrl + JSON.parse(scope.row[item.label])[1].url" 
                                        alt="" 
                                        class="customImg" 
                                    >
                                </span>
                            </p>
                        </code>
                        <code v-else>
                            <code v-if="customSelectSet(item.label, scope.row)">
                                <span
                                    v-for="(k, j) in customSelectList(item.label, scope.row)" :key="j"
                                    :style="customSelectStyle(item.label, scope.row, k)"
                                    class="customSelect"
                                >
                                    {{ k }}
                                </span>
                            </code>
                            <code v-else>
                                <span :style="meritPayCustomSel(item.label, scope.row[item.label])">
                                    {{scope.row[item.label] | setCellData}}
                                </span>
                            </code>
                        </code>
                    </code>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
                <template slot-scope="scope">
                    <el-button type="text" size="small" @click="editData(scope.row)">编辑</el-button>

                    <el-button type="text" size="small" v-if="menu == '产品定义' || menu == '工序'" @click="print(scope.row)">打印</el-button>
                    
                    <el-button type="text" size="small" v-if='menu == "工序"' @click='SOPTemplate(scope.row)'>SOP模板</el-button>  
                   
                    <el-popconfirm :title="delTitle" @confirm='handleDel(scope.row)'>
                        <el-button type="text" size="small" slot="reference" :class="{offset:menu != '工序'}">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
            <div slot="empty">
                <el-empty :image-size="100"></el-empty>
            </div>
        </el-table>
        <el-pagination
            v-if="tableList.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10,20,50,100]"
            :page-size="searchForm.limit"
            layout="total, prev, pager, next, sizes, jumper"
            :total="total"
            background>
        </el-pagination>
        <unitDialog ref='unitDialog' :dialogData='dialogData' :dialogStatus='dialogStatus' @dialogClose='dialogClose'></unitDialog>

        <el-dialog :title="customImgData.title" :visible.sync="customImgData.visible" width='68%'>
            <el-carousel trigger="click" height="50vh" :autoplay='false' :initial-index='customImgData.initial' @change='handleCarousel' ref='carousel'>
                <el-carousel-item v-for="(item, i) in customImgData.list" :key="i">
                    <img :src="item.url" alt="" class='carouselImg'>
                </el-carousel-item>
            </el-carousel>
            <div class='imgDownLoad' @click='imgDownLoad'>
                <span class='el-icon-download'></span>
                下载
            </div>
        </el-dialog>
    </div>
</template>

<script>
import unitDialog from './dialog'
import * as XLSX from "xlsx";
import request from '@/utils/request'
export default {
    props: {
        tableGroup: {
            type: Array,
            default: ''
        },
        searchForm:{
            type:Object,
            default:() => ({})
        },
        tableList: {
            type: Array,
            default: ''
        },
        menu: {
            type: String,
            default: ''
        }
    },
    filters: {
        setCellData(v) {
            let s = false
            let d = []
            try {
                d = (JSON.parse(v)).join(',')
                s = true
            } catch {
                s = false
            }
            if(s) {
                return d
            }
            if(Array.isArray(v)) {
                let arr = []
                v.map(item => {
                    arr.push(item.name)
                })
                return arr.join(',')
            } else {
                return v
            }
        },
        pricingMethod(v) {
            if(v === 0) {
                return '计件'
            } else if(v === 1) {
                return '计时'
            }
        }
    },
    data() {
        return {
            loading: false,
            // 对话框参数
            dialogData: {
              title: '',
              name: '',
              remarks: '',
              defectiveItems_number: '',
              defectiveItems_name: ''
            },
            dialogStatus: false, // 对话框显示隐藏
            currentPage: 1, // 当前页数
            total: null, // 总条数
            delTitle: '',
            customImgData: {
                visible: false,
                list: [],
                title: '',
                initial: 0,
                num: 0
            },
            multipleSelection: [],
            customData: []
        }
    },
    components: {
        unitDialog
    },
    mounted() {
        this.searchForm.limit = 10
        this.searchForm.page = 1
        this.delTitle = this.delMessage(this.menu)
    },
    methods: {
        //接口======================
        handleSortChange() {

        },
        getUrl(data, url) {
            return request({
                url: url,
                method: 'post',
                data,
            })
        },
        getTableData(name, url, type, params) {
            let obj = JSON.parse(JSON.stringify(params))
            obj.limit = 1000
            if(this.multipleSelection.length == 0) {
                let data = obj
                this.getUrl(data, url).then(res => {
                    if(res.code == 200) {
                        if(type === '0') {
                            this.multipleSelection = res.data.records
                            this.multipleSelection.map((item, i) => {
                                item.index = (res.data.current - 1) * 10 + (i + 1)
                                if(item.customFieldVos != null) {
                                    item.customFieldVos.map(k => {
                                        item[k.customFieldId] = k.customFieldMess.fieldType == 'selectChecked' ? JSON.parse(k.value).join(',') : k.value,
                                        item.customType = k.customFieldMess.fieldType
                                    })
                                }
                            })
                        } else if(type == '1') {
                            this.multipleSelection = res.data.list
                            this.multipleSelection.map((item, i) => {
                                item.index = (res.data.pageNum - 1) * 10 + (i + 1)
                                for(let key in item.map) {
                                    item[key] = item.map[key]
                                }
                            })
                        }
                        this.exportTable(name, true)
                    }
                })
            } else {
                this.exportTable(name)
            }
        },
        onTableSelect(rows, row) {
            let selected = rows.length && rows.indexOf(row) != -1
            if(selected == true) {
                this.multipleSelection.push(row)
            } else {
                let d = this.multipleSelection.findIndex(res => { return res.index == row.index })
                this.multipleSelection.splice(d, 1)
            }
        },
        selectAll(val) {
            let data = []
            if(val.length == this.tableList.length) {
                data = this.multipleSelection.concat(val)
            } else if(val.length == 0) {
                this.multipleSelection.map(item => {
                    let d = this.tableList.find(k => { return k.id == item.id })
                    if(d == undefined) {
                        data.push(item)
                    }
                })
            }
            this.multipleSelection = data
        },
        // 编辑
        editData(val) {
            if(this.menu == '单位' || this.menu == '不良品项') {
                this.dialogData.name = val.name
                this.dialogData.comment = val.comment
                this.dialogData.code = val.code
                this.dialogData.id = val.id
                this.dialogData.defectiveItems_number = val.blpxbh
                this.dialogData.defectiveItems_name = val.blpxmc
                this.dialogData.type = this.menu
                this.dialogData.title = '编辑' + this.menu
                this.dialogStatus = true
                this.$refs.unitDialog.fromFather(this.dialogData)
            } else {
                let url = ''
                let obj = {
                    new: false,
                    id: val.id,
                    node: val
                }
                obj.new = false
                if(this.menu == '产品定义') {
                    url = '/basicData/createOrder'
                    obj.new = true
                }
                if(this.menu == '工序') {
                    url = '/basicData/createProcedure'
                    obj.new = true
                }
                if(this.menu == '绩效工资配置') {
                    url = '/basicData/meritPay/createMeritPayRules/edit'
                    obj.new = true
                }
                if(this.menu == '工艺路线') {
                    url = '/basicData/bom/createWorkmanship'
                    obj.new = true
                    obj.list = JSON.stringify(val.list)
                }
                this.$router.push({
                    path: url,
                    query: obj
                })
            }
        },
        // 删除
        handleDel(v) {
            var obj = {
                id: v.id,
                delFlag: 1
            }
            let n = this.multipleSelection.findIndex(res => { return res.id == v.id })
            if(n != -1) {
                this.multipleSelection.splice(n ,1)
            }
            this.$refs.selTable.clearSelection()
            this.multipleSelection.map(item => {
                this.$refs.selTable.toggleRowSelection(item);
            })
            this.$emit('delTableData', obj, this.pageNumber())
        },
        // 对话框关闭后参数
        dialogClose(val, d) {
          this.dialogStatus = val
          if(d) {
              this.$parent.getHandle(d, '编辑成功')
          }
        },
        handleSelectionChange(selection){
            this.$emit('batchRowInfo',selection)
        },
        print(row){
            this.$emit('handlePrint',[row])
        },
        // 分页
        handleSizeChange(val) {
            this.searchForm.limit = val
            this.$emit('getTableData', this.searchForm)
        },
        handleCurrentChange(val) {
            this.searchForm.page = val
            this.$emit('getTableData', this.searchForm)
        },
        // SOP模板
        SOPTemplate(val) {
            let d = val.id
            this.$router.push({
                path: '/basicData/procedure/SOPTemplate',
                query: {
                    name: 'SOP模板',
                    data: d
                }
            })
        },
        totalNum(n) {
            this.total = n
        },
        // 工艺路线详情
        codeDetail(data) {
            this.$router.push({
                path: '/basicData/bom/detail',
                query: {
                    node: JSON.stringify(data)
                }
            })
        },
        onloadLogin(state) {
            this.loading = state
        },
        // 删除提示
        delMessage(t) {
            if(t == '产品定义') return '确认删除产品？操作将同时删除关联的物料清单，删除后不可恢复'
            if(t == '单位') return '确认删除单位？删除后不可恢复'
            if(t == '不良品项') return '确认删除不良品项？删除后不可恢复'
            if(t == '工序') return '确认删除工序？删除后不可恢复'
            if(t == '工艺路线') return '确认删除工艺路线？删除后不可恢复'
            if(t == '绩效工资配置') return '确认删除绩效工资配置？删除后不可恢复'
        },

        // 导出
        exportTable(n, sta) {
            var that = this;
            let dataArr = this.tableGroup.filter(item => item.type != 'picture')
            import("@/excel/export2Excel").then((excel) => {
                const { export_json_to_excel } = require('@/excel/export2Excel'); // 这里必须使用绝对路径，使用@/+存放export2Excel的路径
                let tHeader = dataArr.map(item => { return item.name }); // 导出的表头名信息
                let filterVal = dataArr.map(item => { return item.label }); // 导出的表头字段名，需要导出表格字段名
                let headerStyle = []
                const list = that.multipleSelection;
                let check = dataArr.find(res => { return res.type == 'selectChecked' })
                if(check != undefined) {
                    list.map((item,i) => {
                        if(item[check.label]) {
                            try {
                                item[check.label] = JSON.parse(item[check.label]).join(',')
                            } catch {
                                
                            }
                        }
                    })
                }
                list.map(item => {
                    item.pricing !== undefined ? item.pricing = this.enumCon.pricingMethod(item.pricing) : ''
                    item.pricingMethod !== null ? item.pricingMethod = this.enumCon.pricingMethod(item.pricingMethod) : ''
                    item.attribute !== undefined ? item.attribute = this.enumCon.productAttribute(item.attribute) : ''
                    if(item.vos) {
                        let d = item.vos;
                        let str = []
                        d.map(j => {
                            str.push(j.name)
                        })
                        item.vos = str.join(',')
                    }
                })
                const data = that.formatJson(filterVal, list);
                var sheet = XLSX.utils.json_to_sheet(data, {
                    skipHeader: true,
                });
                for (const key in sheet) {
                    // 第一行，表头
                    if (key.replace(/[^0-9]/ig, '') === '1') {
                        headerStyle.push(key)
                    }
                }
                excel.export_json_to_excel2({
                    header: tHeader,
                    data,
                    filename: n,
                    headerStyle
                });// 导出的表格名称，根据需要自己命名

                if(sta) {
                    this.multipleSelection = []
                }
            });
        },
        formatJson (filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]));
        },

        // 自定义=====================================
        // 自定义字段 复选框/单选框 列
        customSelectSet(t, d) {
            let state = false
            if(d.customFieldVos != null) {
                d.customFieldVos.map(item => {
                    if(item.customFieldMess != null) {
                        if((item.customFieldMess.fieldType == 'selectRadio' || item.customFieldMess.fieldType == 'selectChecked') && t == item.customFieldId) {
                            state = true
                        }
                    }
                })
                return state
            } else {
                return false
            }
        },
        customSelectList(t, d) {
            if(d[t] == '' || d[t] =='[]') {
                return []
            } else {
                let data = []
                try {
                    data =  JSON.parse(d[t])
                } catch {
                    data = d[t].split(',')
                    data[0] == '' ? data = [] : ''
                }
                data === Number(data) ? data = [data] : ''
                return data
            }
        },
        customSelectStyle(t, d, v) {
            let style = {}
            if(d.customFieldVos != null) {
                let obj = d.customFieldVos.find(res => { return res.customFieldId == t })
                if(obj.value != '' && obj.value != '[]' && obj.value != null) {
                    if(obj.customFieldMess.fieldType == 'selectRadio') {
                        let color = JSON.parse(obj.customFieldMess.checkBox).find(res => { return obj.value == res.value })
                        if(color != undefined) {
                            return {
                                color: color.color,
                                background: (color.color).substr(0, 3) + 'a' + (color.color).substr(3, color.color.length - 4) + ', .1)'
                            }
                        } else {
                            return {
                                color: '#333',
                                background: '#f4f4f5'
                            }
                        }
                    }
                    if(obj.customFieldMess.fieldType == 'selectChecked') {
                        let color = JSON.parse(obj.customFieldMess.checkBox).find(res => { return v == res.value })
                        if(color != undefined) {
                            return {
                                color: color.color,
                                background: (color.color).substr(0, 3) + 'a' + (color.color).substr(3, color.color.length - 4) + ', .1)'
                            }
                        } else {
                            return {
                                color: '#333',
                                background: '#f4f4f5'
                            }
                        }
                    }
                }
            }
        },
        // 绩效工资配置自定义字段样式
        // 自定义单选框
        respShowData(data) {
            this.customData = data
        },
        meritPayCustomSel(label, data) {
            if(label == Number(label)) {
                let d = this.customData.find(res => { return res.cusField == label })
                let obj = {}
                if(d != undefined) {
                    JSON.parse(d.customFieldMess.checkBox).map(item => {
                        if(item.value == data) {
                            obj = {
                                color: item.color,
                                background: (item.color).substr(0, 3) + 'a' + (item.color).substr(3, item.color.length - 4) + ', .1)'
                            }
                        }
                    })
                }
                return obj
            }
        },
        // 自定义字段图片列
        customImgSet(t, d) {
            let state = false
            if(d.customFieldVos != null) {
                d.customFieldVos.map(item => {
                    if(item.customFieldMess != null) {
                        if(item.customFieldMess.fieldType == 'picture' && t == item.customFieldId) {
                            state = true
                        }
                    }
                })
                return state
            } else {
                return false
            }
        },
        // 自定义图片预览
        costomImgPreview(i, len, list) {
            this.customImgData.visible = true
            this.customImgData.title = '预览' + ' (' + i + '/' + len + ')'
            this.customImgData.initial = Number(i) - 1
            this.customImgData.list = list.map(item => {
                return {
                    name: item.name,
                    url: this.$global.uploadUrl + item.url
                }
            })
            this.customImgData.num = i - 1
            this.setActiveItem(i - 1)
        },
        setActiveItem(i) {
            if (this.$refs.carousel) {
                this.$refs.carousel.setActiveItem(i)
            }
        },
        // 图片预览轮播切换
        handleCarousel(v) {
            this.customImgData.title = '预览' + ' (' + (Number(v) + 1) + '/' + this.customImgData.list.length + ')'
            this.customImgData.num = v
        },
        // 图片下载
        imgDownLoad() {
            window.open(this.customImgData.list[this.customImgData.num].url, "_blank");
        },
        clearSel() {
            this.multipleSelection = []
        },


        // 当前页
        pageNumber() {
            let totalPage = Math.ceil((this.total - 1) / this.searchForm.limit)
            let currentPage = this.searchForm.page > totalPage ? totalPage : this.searchForm.page
            let page = currentPage < 1 ? 1 : currentPage
            return page
        },
        changeLayout() {
            this.$nextTick(() => {
                this.$refs.selTable.doLayout()
            })
        }
    },
    watch: {
        tableList: {
            handler(val) {
                this.multipleSelection.map(item => {
                    this.$nextTick(() => {
                        val.find(d => {
                            if(d.index == item.index) {
                                this.$refs.selTable.toggleRowSelection(d, true)
                            }
                        })
                    })
                })
            },
            deep: true
        },
        multipleSelection: {
            handler(val) {
                let ids = []
                val.map(item => {
                    ids.push(item.id)
                })
                this.$emit('tableListChecked', ids, this.pageNumber())
            },
            deep: true
        }
    },
    beforeUpdate() {
        this.$nextTick(() => {
            this.$refs.selTable.doLayout()
        })
    }
}
</script>

<style lang="less" scoped>
    .tableList {
        padding: 0 20px;
        
        code{
            font-family: sans-serif;
        }
        .customImg {
            width: 60px;
            height: 60px;
            margin-right: 10px;
            cursor: pointer;
        }

        .offset{
            margin-left: 10px;
        }
        .customImgMoreBox {
            position: relative;
            height: 100%;
            display: inline-block;
            .customImgMore {
                position: absolute;
                left: 0;
                top: 0;
                width: 60px;
                height: 60px;
                background: rgba(0,0,0,.3);
                color: #fff;
                font-size: 10px;
                line-height: 60px;
                text-align: center;
                cursor: pointer;
            }
        }
        .carouselImg {
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
            height: calc(100% - 92px);
        }
        .imgDownLoad {
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
            bottom: 30px;
            background: #02b980;
            color: #fff;
            z-index: 99;
            padding: 5px 10px;
            cursor: pointer;
        }
        .customSelect {
            display: inline-block;
            padding: 0px 6px;
            margin-right: 4px;
            border-radius: 4px;
        }
        .progress {
            display: flex;

            .item_progress {

                .progress_circle {
                    display: flex;
                    align-items: center;

                    .line {
                        width: 30px;
                        height: 2px;
                        background-color: rgb(24, 144, 255);
                        margin: 0px 3px;
                    }
                }

                span {
                    color: #5a5a5a;
                    font-size: 12px;
                    display: inline-block;
                    width: 38px;
                    text-align: center;
                }

                /deep/ .el-progress-circle {
                    width: 38px !important;
                    height: 38px !important;
                }

                /deep/ .el-progress__text {
                    font-size: 12px !important;
                }
            }
        }
    }

    /deep/ .el-table th>.cell {
        line-height: 34px;
    }

    /deep/ .el-table .caret-wrapper {
        float: right;
    }
    /deep/ .el-table th.gutter{
        display: table-cell!important;
    }
    /deep/ .el-carousel__indicators--horizontal {
        display: none;
    }
</style>